// window.opener.location.reload();
var tableIns;
var $;
layui.use(['jquery', 'element', 'table', 'form', 'layer'], function () {
    var element = layui.element;
    $ = layui.jquery;
    var form = layui.form;
    var table = layui.table;
    var layer = layui.layer;
    var createId = localStorage.getItem('createId');
    $('input[name=createId]').val(createId);
    $('input[name=updateId]').val(createId);
    var settingss = {
        view: {
            dblClickExpand: false,
            addDiyDom: addDiyDom
        },
        data: {
            simpleData: {
                enable: true,  //true 、 false 分别表示 使用 、 不使用 简单数据模式
                idKey: "categroyId",   //节点数据中保存唯一标识的属性名称
                pIdKey: "parentId",    //节点数据中保存其父节点唯一标识的属性名称
                rootPId: -1  //用于修正根节点父节点数据，即 pIdKey 指定的属性值
            },
            key: {
                enable: true,
                name: "title"  //zTree 节点数据保存节点名称的属性名称  默认值："name"
            }
        },
        check: {
            enable: false,
            nocheckInherit: true   //当父节点设置 nocheck = true 时，设置子节点是否自动继承 nocheck = true
        },
        callback: {
            onRightClick: onRightClick,
            // beforeRemove: beforeRemove,//点击删除时触发，用来提示用户是否确定删除（可以根据返回值 true|false 确定是否可以删除）
            // beforeEditName: beforeEditName,//点击编辑时触发，用来判断该节点是否能编辑
            beforeRename: beforeRename,//编辑结束时触发，用来验证输入的数据是否符合要求(也是根据返回值 true|false 确定是否可以编辑完成)
            // beforeDrag: beforeDrag,//用户禁止拖动节点
            onClick: chooseNode,
        }
    };
    function addDiyDom(treeId, treeNode) {
        var spaceWidth = 6;
        var switchObj = $("#" + treeNode.tId + "_switch"),
            icoObj = $("#" + treeNode.tId + "_ico");
        switchObj.remove();
        icoObj.parent().before(switchObj);
        var spantxt = $("#" + treeNode.tId + "_span").html();
        if (spantxt.length > 6) {
            spantxt = spantxt.substring(0, 6) + "...";
            $("#" + treeNode.tId + "_span").html(spantxt);
        }
    }
    //鼠标右键功能
    function onRightClick(event, treeId, treeNode) {
        if (treeNode && !treeNode.noR) {
            zTree.selectNode(treeNode);
            showRMenu("node", event.clientX, event.clientY);
        }
    }

    //修改前判断
    function beforeRename(treeId, treeNode, newName) {
        if (newName.length == 0) {
           layer.msg("节点名称不能为空.");
            var zTree = $.fn.zTree.getZTreeObj("ztree");
            setTimeout(function () {
                zTree.editName(treeNode)
            }, 10);
            return false;
        }
        return true;
    }

    function showRMenu(type, x, y) {
        $("#rMenu ul").show();
        if (type == "root") {
            $("#m_del").hide();
        } else {
            $("#m_del").show();
        }

        y += document.body.scrollTop;
        x += document.body.scrollLeft;
        rMenu.css({"top": y + "px", "left": x + "px", "visibility": "visible"});
        $("body").bind("mousedown", onBodyMouseDown);
    }

    function hideRMenu() {
        if (rMenu) rMenu.css({"visibility": "hidden"});
        $("body").unbind("mousedown", onBodyMouseDown);
    }

    function onBodyMouseDown(event) {
        if (!(event.target.id == "rMenu" || $(event.target).parents("#rMenu").length > 0)) {
            rMenu.css({"visibility": "hidden"});
        }
    }

    //添加节点
    addTreeNode = function addTreeNode() {
        hideRMenu();
        var nodes = zTree.getSelectedNodes();
        var parentId = nodes[0].categroyId;
        layer.open({
            type: 1,
            title: "添加节点",
            area: ['400px', '250px'],
            shade: 0.4,
            offset: 'auto',
            content: "<form class='layui-form'><div class='layui-form-item' style='margin: 20px;'>" +
                "<label class='layui-input-label'>添加分类：</label>"
                + "<input type='text' name='title' style='width:220px;height:30px;'id='addNode' lay-verify='required' placeholder='商品分类'>"
                + "</div></form>",
            btn: ['添加', '取消'],
            yes: function () {
                var title = $("#addNode").val();
                var createId = $('input[name=createId]').val();
                var jsProductCategroy = {
                    'parentId': parentId,
                    'title': title,
                    'createId': createId,
                    'categroy': 1,
                }
                $.ajax({
                    url: '/goodsTree/addProductCategroy',
                    dataType: 'json',
                    data: jsProductCategroy,
                    success: function (data) {
                        if (data.data) {
                            layer.msg("添加成功");
                            location.reload();
                        } else {
                            layer.msg("添加失败");
                        }
                    }
                });
            }
        })
    }
    //删除节点
    removeTreeNode = function removeTreeNode() {
        hideRMenu();
        var nodes = zTree.getSelectedNodes();
        var categroyId = nodes[0].categroyId;
        layer.confirm("确认删除" + nodes[0].title + "商品类?",{icon:3,title:'提示'},function (index) {
            if (nodes[0].isParent) {
                layer.msg("不能删除该目录，请从最底层目录开始删除!");
                return false;
            }
            $.ajax({
                url: '/goodsTree/delProductCategroy',
                data: {"categroyId": categroyId},
                dataType: 'json',
                success: function (data) {
                    if (data.data) {
                        layer.msg("删除成功");
                        location.reload();
                        return true;
                    } else {
                        layer.msg("删除失败");
                        return false;
                    }
                }
            });
        })
    }
    //修改节点
    edit = function edit() {
        hideRMenu();
        var nodes = zTree.getSelectedNodes();
        var categroyId = nodes[0].categroyId;
        layer.open({
            type: 1,
            title: '修改节点',
            area: ['400px', '250px'],
            shade: 0,
            offset: 'auto',
            content:"<form class='layui-form'><div class='layui-form-item' style='margin: 20px;'>"+
                "<label class='layui-input-label'>修改分类：</label>"
                +"<input type='text' name='title' style='width:220px;height:30px;'id='updateNode' lay-verify='required' placeholder='商品分类'>"
                +"</div></form>",
            btn : ['确定', '取消'],
            yes: function () {
                var newName = $("#updateNode").val();
                var updateId = $('input[name=updateId]').val();
                var jsProductCategroy = {
                    'categroyId': categroyId,
                    'title': newName,
                    'updateId': updateId
                }
                if (newName.length != 0) {
                    $.ajax({
                        url: '/goodsTree/updateProductCategroy',
                        data: jsProductCategroy,
                        dataType: 'json',
                        success: function (data) {
                            if (data.data) {
                                layer.msg("修改成功");
                                document.location.reload();
                                return true;
                            } else {
                                layer.msg("修改失败");
                                return false;
                            }
                        }
                    });
                } else {
                    layer.msg("不能为空");
                }
            }
        });
    }

    //点击节点，展示对应类别下商品信息
    function chooseNode(event, treeId, treeNode) {
        var zTree = $.fn.zTree.getZTreeObj(treeId);
        var nodes = zTree.getSelectedNodes();
        var jsProduct = {
            'categroyId': treeNode.categroyId,
            'result': '1'
        }
        getTable(jsProduct);
    }

    //加载树
    var zTree, rMenu;
    $(document).ready(function () {
        $.ajax({
            url: "/goodsTree/getTree",
            type: 'post',
            dataType: 'json',
            success: function (data) {
                zTree = $.fn.zTree.init($("#ztree"), settingss, data.data); //初始化树
                zTree.expandAll(true);   //true 节点全部展开、false节点收缩
            }
        })
        rMenu = $("#rMenu");
    });


    //下拉框
    getChanName();
    function getChanName() {
        $.ajax({
            url: "/goodsTree/getTree",
            type: 'post',
            dataType: 'json',
            success: function (data) {
                var d = eval(data.data);
                $("#categroy").append("<option value=''></option>");
                for(var i = 0; i < d.length-1; i++) {
                    var id = d[i].categroyId;
                    var name = d[i].title;
                    $("#categroy").append("<option value='" + id + "'>" + name + "</option>");
                }
                //刷新下拉框
                form.render('select');
            }
        })
    }
    var jsProduct = {
        'result': '1'
    }
    getTable(jsProduct);

    function getTable(jsProduct) {
        $.ajax({
            url: '/goodsTable/getTable',
            type: 'post',
            dataType: 'json',
            data: jsProduct,
            success: function (data) {
                tablereload(data.data);
            }
        });
    }

    tablereload = function tablereload(data) {
        tableIns = table.render({
            elem: '#table',
            data: data,
            title: '数据列表',
            limit: 10,
            id: 'table',
            toolbar: '#toptool',
            page: {
                layout: ['count', 'prev', 'page', 'next', 'skip', 'refresh'],
                first: "首页",
                last: "尾页",
            },
            size: 'lg',
            cols: [[//定义列
                {type: 'checkbox',width:60},//复选框靠左
                {field: 'productCode', title: '商品编号', align: 'center'},
                {
                    field: "mainImage", title: "商品图片", align: 'center',templet: function (data) {
                        return "<img src=' "+ data.mainImage + "' style='width: 100px;height: 100px'/>";
                    }
                },
                {field: 'productName', title: "商品名称", align: 'center'},
                {
                    field: 'currentpriceProduct',
                    title: "商品价格",
                    align: 'center',
                    templet: function (data) {
                        return "￥" + data.currentpriceProduct;
                    }
                },
                {
                    field: 'productSate',
                    title: "上架/下架",
                    align: 'center',
                    templet: function (data) {
                        if (data.productSate == 1) {
                            var radio = '<a href="javascript:updateStatus(' + data.productId + "," + data.productSate + ');"><input class="layui-input swi" type="checkbox" name="sate" lay-skin="switch" lay-text="上架|下架" lay-filter="switchTest" value="' + data.productSate + '" checked></a>'
                        } else {
                            var radio = '<a href="javascript:updateStatus(' + data.productId + ',' + data.productSate + ');"><input class="layui-input swi" type="checkbox" name="sate" lay-skin="switch" lay-text="上架|下架" lay-filter="switchTest" value="' + data.productSate + '"></a>'
                        }
                        return radio;
                    }
                },
                {field: 'title', title: "商品分类", align: 'center'},
                {field: 'productLabel', title: "商品标签", align: 'center'},
                {
                    field: 'result', title: "审核状态", align: 'center', templet: function (data) {
                        if (data.result == 1) {
                            data.result = "审核通过";
                        } else if (data.result == 2) {
                            data.result = "待审核";
                        } else {
                            data.result = "审核未通过";
                        }
                        return "<div style='margin: -8px;height: 28px'>" + data.result + "</div>" +
                            "<a href='javascript:detailed(" + data.productId + ");' style='color: #0EAA9E'>审核详细</a>";
                    }
                },
                {
                    field: '', title: "操作", align: 'center', templet: function (data) {
                        return "<div>" +
                            "<a href='javascript:getProduct(" + data.productId + ");' style='color: #0EAA9E;margin-right: 10px'>查看</a>" +
                            "<a href='javascript:updateProduct(" + data.productId + ");' style='color: #0EAA9E'>编辑</a><br/>" +
                            "<a href='javascript:goGoodsLog();' style='color: #0EAA9E; margin-right: 10px'>日志</a>" +
                            "<a href='javascript:delProduct(" + data.productId + ");' style='color: #0EAA9E'>删除</a>" +
                            "</div>";
                    }
                },
            ]],
        });
    }

    //搜索
    form.on('submit(search)', function (data) {
        $.ajax({
            url: '/goodsTable/getTable',
            type: 'post',
            dataType: 'json',
            data: data.field,
            success: function (data) {
                tablereload(data.data);
            }
        });
    });
    //删除商品
    delProduct = function delProduct(id) {
        layer.confirm('是否确定删除此条数据', {
                icon: 3, title: '提示'
            },
            function (index) {
                //通过id删除表格数据
                $.ajax({
                    url: '/goodsTable/delProduct',
                    type: 'post',
                    dataType: 'json',
                    data: {'productId': id,'updateId':createId},
                    success: function (data) {
                        if (data) {
                            var jsProduct = {
                                'result': '1'
                            }
                            getTable(jsProduct);
                            layer.msg("删除成功");
                        } else {
                            layer.msg("删除失败");
                        }
                    }
                });

            }
        )
    }
    //查看商品详情
    getProduct = function getProduct(productId) {
        $.ajax({
            url: "/goodsTable/getProduct",
            type: "post",
            dataType: "json",
            data: {"productId": productId,'updateId':createId},
            success: function (data) {
                devicesMsg(data);
            },
        })
    }

    function devicesMsg(data) {
        layer.open({
            type: 2,
            title: "查看商品详细",
            area: ['1010px', '450px'],
            maxmin: true,
            shade: 0,
            btn:['关闭'],
            offset: 't',
            content: "/goods/goods-see.html",
            success: function (layero, index) {
                var obj = layero.find('iframe').contents();
                obj.find("#productCode").val(data.data.productCode);
                obj.find("#productName").val(data.data.productName);
                obj.find("#currentpriceProduct").val(data.data.currentpriceProduct);
                obj.find("#title").val(data.data.title);
                if (data.data.productSate == 0) {
                    obj.find("#productSate").val("已删除");
                } else if (data.data.productSate == 1) {
                    obj.find("#productSate").val("上架");
                } else if (data.data.productSate == 2) {
                    obj.find("#productSate").val("下架");
                } else {
                    return "";
                }
                obj.find('#saleNum').val(data.data.saleNum);
                obj.find("#hits").val(data.data.hits);
                obj.find("#collectionNum").val(data.data.collectionNum);
                obj.find("#productDescription").val(data.data.productDescription);
                obj.find("#productLabel").val(data.data.productLabel);
                obj.find("#mainImage").attr('src',data.data.mainImage);
            }
        });
    }

    /*表格详情结束*/
    //开关事件
    updateStatus = function updateStatus(productId, productSate) {
        if (productSate == 1) {
            productSate = 2;
        } else {
            productSate = 1;
        }
        $.ajax({
            url: '/goodsTable/updateProductStatus',
            type: 'post',
            dataType: 'json',
            data: {
                'productId': productId,
                'productSate': productSate
            },
            success: function (data) {
                layer.msg("修改成功");
            }
        })
    }

    /*表格修改开始*/
    updateProduct = function updateProduct(productId) {
        $.ajax({
            url: "/goodsTable/getProduct",
            type: "post",
            dataType: "json",
            data: {"productId": productId,'updateId':createId},
            success: function (data) {
                layer.open({
                    type: 2,
                    title: "修改商品信息",
                    area: ['720px', '450px'],
                    maxmin: true,
                    shade: 0,
                    offset: 't',
                    content: "/goods/goods-update.html",
                    success: function (layero, index) {
                        var obj = layero.find('iframe').contents();
                        obj.find("input[name=productCode]").val(data.data.productCode);
                        obj.find("input[name=productId]").val(data.data.productId);
                        obj.find("input[name=productName]").val(data.data.productName);
                        obj.find("input[name=currentpriceProduct]").val(data.data.currentpriceProduct);
                        var a;
                        if (data.data.productSate == 1) {
                            a = '上架';
                        } else {
                            a = '上架';
                        }
                        selectLay(obj, data.data.productSate, a, '#productSate');
                        obj.find("#productLabel").html(data.data.productLabel);
                        obj.find("#productDescription").html(data.data.productDescription);
                        obj.find("#mainImage").attr('src',data.data.mainImage);
                    }
                });

            }
        });

        //加入lay-value的下拉框矫正
        function selectLay(obj, layValue, value, select) {
            obj.find(select).children().each(function () {
                if ($(this).val() == layValue) {
                    var status = 'dd[lay-value=' + layValue + ']';
                    obj.find(select).siblings("div.layui-form-select").find('dl').find(status).click();
                    $(this).parent().append('<option value="' + layValue + '" selected>' + value + '</option>');
                }
            })
        }
    }
    /*表格修改结束*/
    //高级检索
    retrieval = function retrieval() {
        layer.open({
            type: 2,
            title: "高级检索",
            area: ['600px', '380px'],
            maxmin:true,
            content: "/goods/goods-search-table.html",
            shade: 0,
            offset: 'auto',
            cancel: function(index, layero){
                layer.close(index)
                return false;
            }
        })
    }
    //审核详细
    detailed = function detailed(id) {
        localStorage.setItem('productId', id);
        layer.open({
            type: 2,
            title: '审核详细',
            area: ['700px', '400px'],
            content: '/goods/goods-examine-detailed.html',
            shade: 0,
            maxmin: true,
            offset: 'auto',
        });
    }
    //日志跳转
    goGoodsLog = function goGoodsLog(){
        parent.$('#quickHref').val('商品操作日志');
        parent.getQuick();
        return;
    }
});

//添加商品
function addProduct() {
   layer.open({
       type:2,
       title:'添加商品',
       area: ['1000px', '450px'],
       content: '/goods/goods-add-open.html',
       shade: 0,
       maxmin: true,
       offset: 't',
       btn:['关闭']
   });
}

//刷新
function Refresh() {
    location.reload();
}

//返回
function goBack() {
    //通过页面查找iframe
    parent.$('#quickHref').val('首页');
    parent.getQuick();
    return;
}
